<template>
    <section>
        <div class="step">
            <div class="titles">做任务的步骤（给接单人看的）</div>
            <div class="stepBlock clearfix" v-for="(prop,i) in taskSteps" :key="i">
                <i>{{i+1}}</i>
                <div class="info">
                    <div class="stepBlockTitle">
                        第{{parseChina(i+1)}}步
                        <i v-if="hasCollect(prop)">有收集</i>
                        <el-dropdown class="moreRight" v-if="mode!='preview'"
                            @command="handleStepsUilt"
                        >
                            <span class="el-dropdown-link">
                                <img src="../../static/img/moreCenter.png" />
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                    v-for="utilsItem of stepsUtils"
                                    :key="utilsItem.type"
                                    :command="utilsItem.type + '-' + i"
                                >
                                    {{
                                        utilsItem.name
                                    }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div v-if="prop.length<=0">
                        <div class="noSelect">请点击右边小圆点选择步骤内容</div>
                    </div>
                    <div v-else v-for="(item,index) in prop" :key="index">
                        <!-- 文字介绍 -->
                        <template
                            v-if="item.type=='Description'"
                        >
                            <div class="stepTextarea">
                                <i class="closeStep"
                                    @click="deleteContent(i,index)"
                                    v-if="mode!='preview'"
                                >
                                </i>
                                <el-input
                                    type="textarea"
                                    :rows="4"
                                    :disabled="!isHandleContent"
                                    placeholder="请输入内容"
                                    v-model="item.value"
                                >
                                </el-input>
                            </div>
                        </template>
                        <!-- 图片/视频示例 -->
                        <template
                            v-if="Array.isArray(item)"
                        >
                            <div class="imgVideoList clearfix">
                                <div v-for="(a,ai) in item" :key="ai">
                                    <template v-if="a.type=='Gallery'">
                                        <div class="item up">
                                            <img
                                                :src="isFile(a.uri)=='video'?video2:isFile(a.uri)=='photo'?a.uri:''"
                                            />
                                            <div class="btn">
                                                <template v-if="mode!='preview'">
                                                    <a
                                                        @click="openFile(a.uri)"
                                                    >
                                                        {{ isFile(a.uri) =='video'
                                                            ?'播放视频':isFile(a.uri)=='photo'
                                                            ?'放大':''
                                                        }}
                                                    </a>
                                                    <a
                                                        @click="deleteContent(i,index,ai)">
                                                        删除
                                                    </a>
                                                </template>
                                                <template v-if="mode == 'preview'">
                                                    <a
                                                        @click="openFile(a.uri)"
                                                        :style="{'height':(mode!='preview'?'':'101%')}"
                                                    >
                                                        {{ isFile(a.uri) =='video'
                                                            ?'示例视频':isFile(a.uri)=='photo'
                                                            ?'示例图':''
                                                        }}
                                                    </a>
                                                </template>
                                            </div>
                                        </div>
                                    </template>
                                    <template v-if="a.type=='CollectGallery'">
                                        <template v-if="!a.uri">
                                            <div class="item collectImg">
                                                <span>收集<br />用户的截图</span>
                                                <font color="#3DA1FF"
                                                    @click="deleteContent(i,index,ai)"
                                                    v-if="mode!='preview'"
                                                >
                                                    删除
                                                </font>
                                            </div>
                                        </template>
                                        <template v-if="a.uri">
                                            <div class="item up"
                                                @click="openFile(a.uri)"
                                            >
                                                <img
                                                    :src="isFile(a.uri)=='video'?video2:isFile(a.uri)=='photo'?a.uri:''"
                                                />
                                            </div>
                                        </template>
                                    </template>
                                </div>
                            </div>
                        </template>
                        <!-- 收集用户信息 -->
                        <template
                            v-if="item.type=='CollectTextInfo'"
                        >
                            <div class="collectText" >
                                <h3>收集用户的：</h3>
                                <div class="inputs" :data-clipboard-text="item.placeholder">
                                    <i class="closeStep"
                                        @click="deleteContent(i,index)"
                                        v-if="mode!='preview'"
                                    >
                                    </i>
                                    <template
                                        v-if="mode!='preview'"
                                    >
                                        <el-input
                                            placeholder="请输入收集用户的资料,例如:QQ号码"
                                            v-model="item.placeholder"
                                            :disabled="!isHandleContent"
                                        >
                                        </el-input>
                                    </template>
                                    <template
                                        v-if="mode ==='preview'"
                                    >
                                        <el-input
                                            placeholder="请输入收集用户的资料,例如:QQ号码"
                                            :value="item.value"
                                        >
                                        </el-input>
                                    </template>
                                </div>
                            </div>
                        </template>
                        <!-- 可操作按钮 -->
                        <template v-if="item.type=='Operable'">
                            <div class="linkBlock" >
                                <i class="closeStep"
                                    @click="deleteContent(i,index)"  v-if="mode!='preview'">
                                </i>
                                <div class="textBlock disbox"
                                >
                                    <el-select
                                        v-model="item.target.type"
                                        class="select"
                                        placeholder="请选择" style="width:180px;"
                                        @change="canBtnChange(i,index)"
                                        :disabled="!isHandleContent"
                                    >
                                        <el-option :value="b.name" v-for="(b,bi) in operable" :key="bi" :label="b.name">
                                        </el-option>
                                    </el-select>
                                    <div class="inputs disflex copy_btn" :data-clipboard-text="item.target.value">
                                        <el-input
                                            :placeholder="'请输入' + item.target.type"
                                            v-model="item.target.value"
                                        >
                                        </el-input>
                                    </div>
                                </div>
                                <div class="needBtn clearfix">
                                    <h3>操作内容</h3>
                                    <template
                                        v-for="(btnItem,btnIndex) of item.target.content"
                                    >
                                        <a class="btn"
                                        :key="btnIndex + 'useBtn'"
                                        >
                                            {{ btnItem.name ? btnItem.name : btnItem}}
                                        </a>
                                    </template>
                                    <div v-if="item.target.content==0" class="noBtns">暂无任何操作</div>
                                    <!-- <div v-if="(operable.findIndex((oitem)=>item.target.type==oitem.name))==-1" class="noBtns">
                                        当前选择的类型于服务器不匹配（可能是后台删除了xx类型导致的）
                                    </div> -->
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
        <div class="nor" :class="taskSteps.length<=0?'no':''">
            <template v-if="taskSteps.length<=0">暂无步骤 </template>
            <a class="addStep blue" @click="addStep" v-if="mode!='preview'"> 添加步骤</a>
        </div>
        <input type="file"
            ref="uploadImg"
            @change="handleUploadImg"
            style="display: none"
            accept="image/*,video/*"
        />
    </section>
</template>
<script>
import md5 from "js-md5";
import ClipboardJS from "clipboard";
import nzh from "nzh";
import uilts from '@/utils/index';
import compressImg from '@/utils/compressImg';
// 请求通用方法
import apiMixin from '@/mixin/apiMixin';
export default {
    mixins: [apiMixin],
    props: {
        mode: String, //systemTemplate代表系统模板    userTemplate代表用户模板    edit普通编辑模式     preview普通预览模式
        taskSteps: {
            type: Array,
            default: () => {
                return [];
            }
        },
        uploadBids: Array
    },
    data() {
        return {
            // 操作对象
            operable: {},
            stepsUtils: [
                {
                    name: '添加介绍文字',
                    type: 'addText'
                },
                {
                    name: '添加示例图/视频',
                    type: 'addFile'
                },
                {
                    name: '添加可操作的按钮',
                    type: 'addHeBtn'
                },
                {
                    name: '收集用户文字',
                    type: 'collectText'
                },
                {
                    name: '收集用户图片',
                    type: 'collectImg'
                },
                {
                    name: '删除本列',
                    type: 'delete'
                },
                {
                    name: '上移',
                    type: 'moveUp'
                },
                {
                    name: '下移',
                    type: 'moveDown'
                },
            ],
            curHandStepIndex: null,
            bid: '',
        }
    },
    created() {
        this.bid = uilts.createBidFn();
        this.getCanHandleBtnApi();
    },
    computed: {
        isHandleContent() {
            return true;
            // if (this.mode === 'preview') {
            //     return false;
            // }
            // return true;
        }
    },
    methods: {
        hasCollect(prop) {
            return JSON.stringify(prop).indexOf('Collect') != -1
        },
        parseChina(num) {
            //将数字转换为大写语文
            return nzh.cn.encodeS(num);
        },
        openFile(url) {
            //打开文件
            open(url, "_blank");
        },
        parseChina(num) {
            //将数字转换为大写语文
            return nzh.cn.encodeS(num);
        },
        addStep() {
            if (!this.checkCanHandleStep) {
                return;
            }
            this.taskSteps.push([]);
        },
        deleteContent(stepIndex,ctIndex,fileIndex) {
            if (fileIndex){
                this.taskSteps[stepIndex][ctIndex].splice(fileIndex,1);
            }else{
                this.taskSteps[stepIndex].splice(ctIndex,1);
            }
            if (this.taskSteps[stepIndex].length <= 0 ) {
                this.taskSteps.splice(stepIndex,1);
            }
        },
        handleStepsUilt(typeStr) {
            if (!this.checkCanHandleStep) {
                return;
            }
            let stayStr = typeStr.split('-');

            let type = stayStr[0];
            let stepIndex = stayStr[1];

            let steps = uilts.simpleCopy(this.taskSteps);
            let curStep = steps[stepIndex];

            let _self = this;
            let soltObj = {
                // 添加介绍文字
                'addText': () => {
                    _self.taskSteps[stepIndex].push(
                        {type:'Description',value:''}
                    );
                },
                // 添加示例图/视频
                'addFile': () => {
                    _self.curHandStepIndex = stepIndex;
                    _self.triggerUploadClick();
                },
                // 添加可操作的按钮
                'addHeBtn': () => {
                    let operableTargets = this.operable;
                    _self.taskSteps[stepIndex].push(
                        {
                            type:'Operable',
                            target: {
                                type: operableTargets[0].name,
                                content:  operableTargets[0].btns
                            }
                        }
                    );
                },
                // 收集用户文字
                'collectText': () => {
                    _self.taskSteps[stepIndex].push(
                        {type:'CollectTextInfo',placeholder: '', value: ''}
                    );
                },
                // 收集用户图片
                'collectImg': () => {
                    if (Array.isArray(curStep[curStep.length -1 ])){
                        curStep[curStep.length -1 ].push({
                            type:"CollectGallery",
                            uri: '',
                        });
                    }else{
                        curStep.push([{
                            type:"CollectGallery",
                            uri: '',
                        }])
                    }
                    _self.$set(_self.taskSteps,stepIndex,curStep);
                },
                // 删除本列
                'delete': () => {
                    _self.taskSteps.splice(stepIndex,1)
                },
                // 上移
                'moveUp': () => {
                    _self.changeSort(stepIndex,0);
                },
                // 下移
                'moveDown': () => {
                    _self.changeSort(stepIndex,1);
                }
            }
            soltObj[type]();
        },
        changeSort (index, type) {
            if(type==0&&index==0){
                this.$message.error('已经是第一步了！')
                return;
            }
            if(type==1&&index==this.taskSteps.length-1){
                this.$message.error('已经是最后一步了！')
                return;
            }
            let changIndex = null;
            index = Number(index);
            if (type==0) {
                changIndex = index - 1;
            }else{
                changIndex = index + 1;
            }
            let changeStep = this.taskSteps[changIndex];
            let curStep =  this.taskSteps[index];
            this.$set(this.taskSteps,changIndex,curStep);
            this.$set(this.taskSteps,index,changeStep);
        },
        handleUploadImg(e) {
            console.log(e);
            if (e.target.files.length === 0) {
                return;
            }
            let file = e.target.files[0];
            if(!this.isFile(file.name)){
                this.toast('不支持此文件类型上传！')
                return;
            }
            let _self = this;
            let data = new FormData();
            const margeImgsFn = (res) => {
                if (!_self.uploadBids[0]) {
                    _self.uploadBids.push(_self.bid);
                }
                let curIndex = _self.curHandStepIndex;
                let curStep = JSON.parse(JSON.stringify(_self.taskSteps[curIndex]));
                let url = res.data.url;
                if (Array.isArray(curStep[curStep.length -1 ])) {
                    curStep[curStep.length -1 ].push({
                        type:"Gallery",
                        uri:url,
                        fid:res.data.id
                    });
                }else{
                    curStep.push([{
                        type:"Gallery",
                        uri:url,
                        fid:res.data.id
                    }]);
                }
                _self.$set(_self.taskSteps,curIndex,curStep);
            }
            const uploadImgApi = (resPar) => {
                _self.request.uploadFile(resPar).then((res)=>{
                    console.log(res);
                    margeImgsFn(res.data);
                }).catch((ero)=>{

                });
            }
            if (file.type.indexOf('video') != -1) {
                data.append('bid',uilts.getUploadPrefix('video') + '-' +_self.bid);
                data.append('file', file);
                uploadImgApi(data);
            }else{
                data.append('bid',uilts.getUploadPrefix() + '-' +_self.bid);
                compressImg(file).then((resFile)=>{
                    data.append('file', resFile.content);
                    uploadImgApi(data);
                })
            }
        },
        triggerUploadClick() {
            this.$refs.uploadImg.value = '';
            this.$refs.uploadImg.click();
        },
        /**
         *  检测是否可以修改步骤
         */
        checkCanHandleStep() {
            return true;
        },
        getCanHandleBtnApi() {
            let _self = this;
            const parseCanUSeData = (target,oprations) => {
                for (let i=0;i<target.length;i++) {
                    let curTarget = target[i];
                    curTarget.btns = [];
                    let operationsList = curTarget.operations.split(',');
                    for (let opIndex = 0;opIndex<operationsList.length;opIndex++) {
                        let opValue = operationsList[opIndex];
                        if (oprations[opValue]) {
                            curTarget.btns.push(oprations[opValue].h5_name)
                        }
                    }
                };
                return target;
            }
            this.comResquest(this.request.getCanHandleBtn,(res)=>{
                console.log(res);
                let useTarget = parseCanUSeData(res.result_target,res.result_oprations);
                _self.operable = useTarget;
                console.log(useTarget);
            },{});
        },
        canBtnChange(stepIndex,ctIndex) {
            let taskSteps = uilts.simpleCopy(this.taskSteps);
            let curStep = taskSteps[stepIndex];
            let curCt = curStep[ctIndex];
            let operableTargets = this.operable;
            for (let otIndex=0;otIndex<operableTargets.length;otIndex++) {
                let curOt = operableTargets[otIndex];
                if (curCt.target.type === curOt.name) {
                    curCt.target.content = curOt.btns;
                }
            }
            this.$set(this.taskSteps,stepIndex,curStep);
        },
    }
}
</script>

<style lang="scss" scoped>
.titles{
    margin-top:25px;
    margin-bottom:12px;
    font-size:19px;
}
.stepBlock {
    margin-top: 30px;
    & > i {
        float: left;
        background: #f7ca8a;
        color: #000;
        width: 25px;
        height: 25px;
        line-height: 25px;
        text-align: center;
        border-radius: 50%;
        font-style: normal;
        font-size: 13px;
    }
    .info {
        float: left;
        width: calc(100% - 25px);
        padding-left: 20px;
        .stepBlockTitle {
            font-size: 16px;
            height: 25px;
            line-height: 25px;
            position:relative;
            i {
                background: #f30;
                color: #fff;
                font-style: normal;
                font-size: 13px;
                padding: 5px 11px;
                border-radius: 30px;
                margin-left: 20px;
                vertical-align: middle;
                margin-top: -2px;
            }
            img {
                float: right;
                height: 23px;
                cursor: pointer;
                padding: 9px 0;
            }
        }
        .noSelect {
            color: #c2c2c2;
            line-height: 35px;
            margin-top: 10px;
            font-size: 15px;
            font-weight: 300;
        }
        .stepTextarea {
            display: block;
            width: 100%;
            margin-top: 26px;
            position: relative;
            textarea {
                font-size: 15px;
                padding: 10px 15px;
                line-height: 30px;
            }
        }
        .collectText {
            margin-top: 15px;
            & > h3 {
                font-weight: 300;
                height: 35px;
                line-height: 35px;
                margin-bottom: 10px;
                font-size: 15px;
            }
            & > .inputs {
                position: relative;
            }
        }
        .imgVideoList {
            margin-top: 25px;
            margin-bottom: -10px;
            .item {
                float: left;
                margin-right: 20px;
                margin-bottom: 20px;
                position: relative;
                width: 160px;
                height: 160px;
                &.up {
                    img {
                        display: block;
                        width: 100%;
                        height: 100%;
                    }
                    .btn {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0, 0, 0, 0.3);
                        a {
                            cursor: pointer;
                            display: block;
                            width: 100%;
                            text-align: center;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            flex-direction: column;
                            font-weight: 300;
                            height: 50%;
                            color: #fff;
                            font-size: 15px;
                            position: relative;
                            &:nth-child(1):after {
                                position: absolute;
                                width: 50%;
                                background: #fff;
                                height: 1px;
                                left: 25%;
                                bottom: 0;
                                content: " ";
                            }
                        }
                    }
                }
                &.collectImg {
                    border: 1px dashed #eeeeee;
                    background: #f9f9f9;
                    font-weight: 300;
                    color: #b4b4b4;
                    text-align: center;
                    line-height: 35px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    font-size: 15px;
                    font {
                        cursor: pointer;
                    }
                }
            }
        }
        .linkBlock {
            position: relative;
            background: #f6f6f6;
            padding: 18px;
            margin-top: 25px;
            .textBlock {
                .select {
                    height: 38px;
                    display: block;
                    font-weight: 300;
                    line-height: 38px;
                    text-align: center;
                    font-size: 15px;
                    color: #000;
                    div {
                        overflow: hidden;
                        img {
                            width: 15px;
                            margin-left: 10px;
                            vertical-align: middle;
                        }
                    }
                }
                .inputs {
                    margin-left: 15px;
                    height: 38px;
                    position: relative;
                    text-align: center;
                    input {
                        display: block;
                        width: 100%;
                        height: 38px;
                        font-weight: 300;
                        font-size: 15px;
                        line-height: 20px;
                        padding: 9px 15px;
                    }
                }
            }
            .needBtn {
                background: #fff;
                margin-top: 30px;
                position: relative;
                padding: 20px;
                h3 {
                    font-weight: 300;
                    position: absolute;
                    height: 40px;
                    line-height: 40px;
                    top: -20px;
                    left: 20px;
                    font-size: 15px;
                }
                .btn {
                    font-weight: 300;
                    margin-top: 15px;
                    float: left;
                    color: #1e1e1e;
                    border: 1px solid #ececec;
                    border-radius: 4px;
                    padding: 0 20px;
                    margin-right: 15px;
                    font-size: 14px;
                    height: 30px;
                    line-height: 28px;
                    img {
                        width: 12px;
                        vertical-align: middle;
                        margin-top: -2px;
                        margin-left: 10px;
                    }
                }
            }
        }
    }
}
.nor {
    text-align: right;
}
.no{
    text-align:left!important;
    font-size: 15px;
    color:#595959;
    margin-top:20px;
    display: block;
}
.addStep {
    font-size: 14px;
    margin-top: 20px;
    display: inline-block;
    cursor: pointer;
}
.moreRight{
    vertical-align: middle;
    float:right;
}
.closeStep {
    background: url("../../static/img/closeStep.png") no-repeat center center;
    position: absolute;
    right: -10.5px;
    top: -10.5px;
    width: 21px;
    height: 21px;
    border-radius: 50%;
    background-size: 100%;
    z-index: 1;
    cursor: pointer;
}
</style>
